import 'package:ai/AppRouter.gr.dart';
import 'package:ai/response/TextRecordResponse.dart';
import 'package:ai/service/TextRecordService.dart';
import 'package:ai/util/CommonUtils.dart';
import 'package:auto_route/annotations.dart';
import 'package:flutter/material.dart';

@RoutePage()
class TextWriteRecord extends StatefulWidget {
  final int textAppId;

  const TextWriteRecord({super.key, required this.textAppId});

  @override
  State<TextWriteRecord> createState() => _TextWriteRecordState();
}

class _TextWriteRecordState extends State<TextWriteRecord> {
  List<TextRecord> _items = [];
  final ScrollController _scrollController = ScrollController();
  bool _isLoadingMore = false;
  int _pageNumber = 1;

  final TextRecordService _textRecordService = TextRecordService();

  @override
  void initState() {
    super.initState();
    load(_pageNumber);
    _scrollController.addListener(() {
      if (_scrollController.position.pixels >=
          _scrollController.position.maxScrollExtent - 300) {
        _loadMoreItems();
      }
    });
  }

  void load(int pageNumber) {
    _textRecordService.list(widget.textAppId, pageNumber).then((result) {
      setState(() {
        if (pageNumber == 1) {
          _items = result;
        } else {
          List<TextRecord> list = [];
          list.addAll(_items);
          list.addAll(result);
          _items = list;
        }
        _pageNumber = pageNumber;
        _isLoadingMore = false;
      });
    });
  }

  Future<void> _refreshItems() async {
    load(1);
  }

  void _loadMoreItems() async {
    if (_isLoadingMore) return;
    setState(() {
      _isLoadingMore = true;
    });
    load(_pageNumber + 1);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.white,
        title: const Text("历史记录"),
        leading: BackButton(
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16),
        child: RefreshIndicator(
          onRefresh: _refreshItems,
          child: ListView.builder(
            controller: _scrollController,
            itemCount: _items.length + (_isLoadingMore ? 1 : 0),
            itemBuilder: (context, index) {
              if (index == _items.length) {
                return const Center(child: CircularProgressIndicator());
              }
              return ListTile(
                onTap: (){
                  CommonUtils.go(context, TextRecordDetail(textTaskId:_items[index].id));
                },
                title: Text(_items[index].title),
                subtitle: Text(_items[index].createdDate),
              );
            },
          ),
        ),
      ),
    );
  }
}
